#include <stdio.h>
#include <poll.h>

int main() {
    struct pollfd fds[2];
    int nfds = 2;
    int ret;

    fds[0].fd = 0;  // stdin
    fds[0].events = POLLIN;
    fds[1].fd = 1;  // stdout
    fds[1].events = POLLOUT;

    while (1) {
        ret = poll(fds, nfds, -1);
        if (ret == -1) {
            perror("poll error");
            break;
        } else if (ret == 0) {
            // 超时
            continue;
        } else if (fds[0].revents & POLLIN) {
            // 有输入数据
            char buf[1024];
            read(0, buf, sizeof(buf));
            printf("Received data: %s\n", buf);
        } else if (fds[1].revents & POLLOUT) {
            // 有输出空间
            char buf[1024] = "Hello, world!";
            write(1, buf, strlen(buf));
        }
    }

    return 0;
}
